package com.yihaodian.search.query;

import java.util.Collections;

import org.apache.log4j.Logger;
import org.apache.lucene.search.Query;
import org.apache.solr.core.SolrCore;
import org.apache.solr.request.LocalSolrQueryRequest;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.search.QParser;
import org.apache.solr.search.QParserPlugin;
import org.apache.solr.search.SyntaxError;

import com.yihaodian.api.search.SearchRequest;
import com.yihaodian.index.solr.SolrSearcher;
import com.yihaodian.search.SearchContext;
import com.yihaodian.search.core.SearchHandler;
import com.yihaodian.search.query.converter.QueryConverter;

/**
 * query process
 * 
 */
public class QueryBuilder {
	static Logger logger = Logger.getLogger(SearchHandler.class);

	public void handle(SearchContext context) {
		SearchRequest searchRequest = context.getShardRequest().getSearchRequest();
		String querySyntax = searchRequest.getQuerySyntax();
		if (querySyntax == null) {
			Query query = QueryConverter.convert(searchRequest.getQuery());
			querySyntax = query.toString();
		}

		SolrSearcher searcher = (SolrSearcher) context.getSearcher();
		Query solrQuery = solrQueryParsing(searcher.getSolrCore(), querySyntax);
		context.setQuery(solrQuery);
	}

	Query solrQueryParsing(SolrCore solrCore, String queryStr) {
		SolrQueryRequest request = new LocalSolrQueryRequest(solrCore,
				Collections.EMPTY_MAP);
		try {
			QParser parser = QParser.getParser(queryStr,
					QParserPlugin.DEFAULT_QTYPE, request);
			Query query = parser.getQuery();

			logger.info("solr query: " + query);
			return query;
		} catch (SyntaxError e) {
			logger.error(e, e);
		}

		return null;
	}

}
